package com.lhj.security.config;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.lhj.security.config.security.UserAuthDetail;
import com.lhj.security.entity.UserEntity;
import com.lhj.security.enums.RoleTypeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

import java.util.Arrays;
import java.util.concurrent.TimeUnit;

@Slf4j
@Configuration
public class GuavaConfig {
    

    // 令牌有效期（默认30分钟）
    @Value("${token.expireTime}")
    private int expireTime;

    private PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
    
    @Bean(name = "userCache")
    public Cache<String, UserEntity> userCache() {
        Cache<String, UserEntity> cache = CacheBuilder.newBuilder()
                .expireAfterWrite(365, TimeUnit.DAYS)
                .build();
        UserEntity adminEntity = UserEntity.builder()
                .userName("lhj")
                .password(passwordEncoder.encode("password"))
                .roles(Arrays.asList(RoleTypeEnum.ADMIN))
                .build();
        

        UserEntity userEntity = UserEntity.builder()
                .userName("liuyan")
                .password(passwordEncoder.encode("123"))
                .roles(Arrays.asList(RoleTypeEnum.USER))
                .build();

        log.info("测试账密01 lhj/password 权限；admin");
        log.info("测试账密02 liuyan/123 权限；user");

        cache.put(adminEntity.getUserName(), adminEntity);
        cache.put(userEntity.getUserName(), userEntity);
        return cache;
    }


    @Bean(name = "userAuthDetail")
    public Cache<String, UserAuthDetail> userAuthDetail() {
        return CacheBuilder.newBuilder()
                .expireAfterWrite(expireTime, TimeUnit.MINUTES)
                .build();
    }
}
